package com.moss.cloud.common.core.utils;

import com.moss.cloud.common.core.constant.Constant;
import com.moss.cloud.common.core.exception.SystemErrorType;
import org.apache.commons.collections4.CollectionUtils;

import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>树形菜构建工具</p>
 *
 * @author songLei
 * @date 2020年11月26日
 */
public class TreeUtil {
    /**
     * 通用树转换
     *
     * @param treeList    集合
     * @param id          顶级节点ID
     * @param getId       唯一属性
     * @param getParentId 父级节点属性
     * @param setChildren 孩子节点属性
     * @param <T>         泛型
     * @return
     */
    public static <T> List<T> toTree(List<T> treeList, Long id, Function<T, Long> getId, Function<T, Long> getParentId, BiConsumer<T, List<T>> setChildren) {
        return CollectionUtils.isNotEmpty(treeList) && !getParentId.apply(treeList.get(0)).equals(0L) ? treeList : treeList.stream()
                .filter(node -> getParentId.apply(node).equals(id))
                .peek(node -> {
                    List<T> children = toTree(treeList, getId.apply(node), getId, getParentId, setChildren);
                    setChildren.accept(node, children);
                })
                .collect(Collectors.toList());
    }

    public static void checkSort(int sort) {
        BooleanHandel.trueThrow(Constant.ZERO == sort).throwMessage(SystemErrorType.SORT_VALUE);
    }
}
